<template>
  <ContentWrap>

    <el-tabs v-model="activeName" class="demo-tabs" @tab-change="tabClickHandle">

      <el-tab-pane label="待提现" name="0" />
      <el-tab-pane label="待审核" name="5" />
      <el-tab-pane label="已完成" name="1" />
      <el-tab-pane label="全部" name="" />
    </el-tabs>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-30px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="100px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="客人姓名" prop="guestName">
        <el-input v-model="queryParams.guestName" placeholder="请输入客人姓名" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="计划入住时间" prop="plannedCheckIn">
        <el-date-picker v-model="queryParams.plannedCheckIn" value-format="YYYY-MM-DD" type="date"
          placeholder="选择计划入住时间" clearable class="!w-260px" />
      </el-form-item>
      <el-form-item label="计划离店时间" prop="plannedCheckOut">
        <el-date-picker v-model="queryParams.plannedCheckOut" value-format="YYYY-MM-DD" type="date"
          placeholder="选择计划离店时间" clearable class="!w-260px" />
      </el-form-item>
      <el-form-item label="实际住宿夜数" prop="actualNights">
        <el-input v-model="queryParams.actualNights" placeholder="请输入实际住宿夜数" clearable @keyup.enter="handleQuery"
          class="!w-260px" />
      </el-form-item>
      <el-form-item label="实际离店日期" prop="actualCheckoutDate">
        <el-date-picker v-model="queryParams.actualCheckoutDate" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-260px" />
      </el-form-item>

      <el-form-item label="提现状态" prop="withdrawStatus">
        <el-select v-model="queryParams.withdrawStatus" placeholder="请选择提现状态" clearable class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.WITHDRAWAL_STATUS_TYPE)" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" type="primary">
          <Icon icon="ep:search" class="mr-5px" /> 查询
        </el-button>
        <el-button @click="resetQuery" type="primary">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <!--<el-button type="primary" plain @click="openForm('create')" v-hasPermi="['hotel:order-withdrawal:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>-->
        <!-- <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['hotel:order-withdrawal:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>-->
      </el-form-item>
    </el-form>
  </ContentWrap>


  <!-- 财务看板 -->
  <ContentWrap>
    <div class="financial-dashboard">
      <div class="dashboard-title">财务看板</div>
      <el-row :gutter="20">
        <!-- 待提现订单 -->
        <el-col :span="4">
          <el-card class="dashboard-card">
            <div class="dashboard-item">
              <div class="dashboard-icon">
                <Icon icon="ep:document" class="icon-waiting" />
              </div>
              <div class="dashboard-content">
                <div class="dashboard-title">待提现订单</div>
                <div class="dashboard-value">{{ dashboardData.waitingWithdrawOrderCount || 0 }}</div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 待提现金额 -->
        <el-col :span="4">
          <el-card class="dashboard-card">
            <div class="dashboard-item">
              <div class="dashboard-icon">
                <Icon icon="ep:coin" class="icon-amount" />
              </div>
              <div class="dashboard-content">
                <div class="dashboard-title">待提现金额</div>
                <div class="dashboard-value">¥{{ dashboardData.waitingWithdrawAmount || 0 }}</div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 审核中订单 -->
        <el-col :span="4">
          <el-card class="dashboard-card">
            <div class="dashboard-item">
              <div class="dashboard-icon">
                <Icon icon="ep:document-checked" class="icon-review" />
              </div>
              <div class="dashboard-content">
                <div class="dashboard-title">审核中订单</div>
                <div class="dashboard-value">{{ dashboardData.reviewingOrderCount || 0 }}</div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 提现审核中金额 -->
        <el-col :span="4">
          <el-card class="dashboard-card">
            <div class="dashboard-item">
              <div class="dashboard-icon">
                <Icon icon="ep:money" class="icon-review-amount" />
              </div>
              <div class="dashboard-content">
                <div class="dashboard-title">提现审核中金额</div>
                <div class="dashboard-value">¥{{ dashboardData.reviewingAmount || 0 }}</div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 酒店收款信息 -->
        <el-col :span="8">
          <el-card class="dashboard-card">
            <div class="dashboard-item">
              <div class="dashboard-content">
                <div class="dashboard-title">酒店收款信息</div>
                <div class="dashboard-details">
                  <div class="detail-row">
                    <span class="label">账户名称：</span>
                    <span class="value">{{ dashboardData.accountName || '-' }}</span>
                  </div>
                  <div class="detail-row">
                    <span class="label">银行账户：</span>
                    <span class="value">{{ dashboardData.bankAccount || '-' }}</span>
                  </div>
                  <div class="detail-row">
                    <span class="label">开户银行：</span>
                    <span class="value">{{ dashboardData.bankName || '-' }}</span>
                  </div>
                  <div class="detail-row">
                    <span class="label">支行名称：</span>
                    <span class="value">{{ dashboardData.branchName || '-' }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </ContentWrap>
  <ContentWrap>
    <!-- 批量信息展示 -->
    <div class="batch-info">
      <el-row>
        <el-col :span="2">
          <el-button type="primary" @click="handleBatchWithdraw">
            批量提现
          </el-button></el-col>
        <!--todo 给金额增加颜色和大小-->
        已选择{{ selectedOrders.length || 0 }}笔，
        订单实付: ￥{{ formatMoney(totalPaidAmount) || 0 }},
        退款金额: ￥{{ formatMoney(totalRefundAmount) || 0 }},
        实收金额: ￥{{ formatMoney(totalReceivedAmount) || 0 }},
        平台佣金: ￥{{ formatMoney(totalCommission) || 0 }},
        结算金额: ￥{{ formatMoney(totalSettlementAmount) || 0 }}
      </el-row>
    </div>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderNo">
        <template #default="scope">
          <el-button link type="primary" @click="openDetail(scope.row)">
            {{ scope.row.orderNo }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="客人姓名" align="center" prop="guestName" />
      <el-table-column label="房型名称" align="center" prop="roomType" />
      <el-table-column v-if="false" label="计划入住时间" align="center" prop="plannedCheckIn" :formatter="dateFormatter" width="180px" />
      <el-table-column v-if="false" label="计划离店时间" align="center" prop="plannedCheckOut" :formatter="dateFormatter" width="180px" />
     <el-table-column label="计划入离时间" align="center" width="220px">
      <template #default="scope">
        {{ dateFormatter1(scope.row.plannedCheckIn) }} - {{ dateFormatter1(scope.row.plannedCheckOut) }}
      </template>
    </el-table-column>
      <el-table-column label="实际住宿夜数" align="center" prop="actualNights" />
      <el-table-column label="实际离店日期" align="center" prop="actualCheckoutDate" />
      <el-table-column label="订单实付金额（元）" align="center" prop="amountPaid" />
      <el-table-column label="退款金额（元）" align="center" prop="refundAmount" />
      <el-table-column label="订单实收金额" align="center" prop="amountReceived" />
      <el-table-column label="平台佣金（元）" align="center" prop="platformCommission" />
      <el-table-column label="结算金额" align="center" prop="settlementAmount" />
      <el-table-column label="提现状态" align="center" prop="withdrawStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.WITHDRAWAL_STATUS_TYPE" :value="scope.row.withdrawStatus" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="操作" align="center">
        <!-- <template #default="scope">
             <el-button link type="primary" @click="openForm('update', scope.row.id)"
            v-hasPermi="['hotel:order-withdrawal:update']">
            编辑
          </el-button>
             <el-button link type="danger" @click="handleDelete(scope.row.id)"
            v-hasPermi="['hotel:order-withdrawal:delete']">
            删除
          </el-button> 
        </template>-->

        <template #default="scope">
          <el-button v-if="scope.row.withdrawStatus === 0" link type="primary"
            @click="handleWithdraw(scope.row.orderNo)">
            去提现
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改
  <OrderWithdrawalForm ref="formRef" @success="getList" /> -->
  <OrderWithdrawalDetail ref="detailRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter, dateFormatter1 } from '@/utils/formatTime'
import download from '@/utils/download'
import * as OrderWithdrawalApi from '@/api/hotel/orderwithdrawal'
import OrderWithdrawalForm from './OrderWithdrawalForm.vue'
import OrderWithdrawalDetail from './OrderWithdrawalDetail.vue'
import { number } from 'vue-types'

defineOptions({ name: 'OrderWithdrawal' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  orderNo: undefined,
  guestName: undefined,
  roomType: undefined,
  plannedCheckIn: undefined,
  plannedCheckOut: undefined,
  actualNights: undefined,
  actualCheckoutDate: [],
  amountPaid: undefined,
  refundAmount: undefined,
  amountReceived: undefined,
  platformCommission: undefined,
  settlementAmount: undefined,
  withdrawStatus: undefined,
  createdAt: undefined,
  updatedAt: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await OrderWithdrawalApi.getOrderWithdrawalPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList();
  getDashboardData();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}
// 详情弹窗相关
const detailRef = ref()

// 打开详情弹窗
const openDetail = (row: any) => {
  detailRef.value.open(row)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await OrderWithdrawalApi.deleteOrderWithdrawal(id)
    message.success(t('common.delSuccess'))
    // 刷新列表

    await getList()
  } catch { }
}
const handleWithdraw = async (orderNo: string) => {
  try {
    const result: boolean = await OrderWithdrawalApi.handleWithdraw(orderNo);
    if (result) {
      message.success("提现已成功提交");
      getList();
    } else {
      message.error("提现提交失败，请稍后再试");
      getList();
    }

  } catch (msg: any) {
    message.error("提现失败" + msg);
    console.log("提现失败" + msg);
  };

}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await OrderWithdrawalApi.exportOrderWithdrawal(queryParams)
    download.excel(data, '订单提现.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const dashboardData = ref<any>({});

const getDashboardData = async () => {
  try {
    const data = await OrderWithdrawalApi.getFinancialDashboard()
    dashboardData.value = data
  } catch (error) {
    console.error('获取财务看板数据失败:', error)
  }
}
/** 初始化 **/
onMounted(() => {
  getDashboardData();
  getList()
})

// 当前选中的订单列表
const selectedOrders = ref<any[]>([])

// 处理选中变化
const handleSelectionChange = (selection: any[]) => {
  selectedOrders.value = selection
}

// 计算总金额（使用 computed 更高效）
const totalPaidAmount = computed(() => {
  return selectedOrders.value.reduce((sum, item) => sum + item.amountPaid, 0)
})

const totalRefundAmount = computed(() => {
  return selectedOrders.value.reduce((sum, item) => sum + item.refundAmount, 0)
})

const totalReceivedAmount = computed(() => {
  return selectedOrders.value.reduce((sum, item) => sum + item.amountReceived, 0)
})

const totalCommission = computed(() => {
  return selectedOrders.value.reduce((sum, item) => sum + item.platformCommission, 0)
})

const totalSettlementAmount = computed(() => {
  return selectedOrders.value.reduce((sum, item) => sum + item.settlementAmount, 0)
})

const formatMoney = (value: number): string => {
  return Number(value || 0).toFixed(2)
}


// 批量提现处理
const handleBatchWithdraw = () => {
  if (selectedOrders.value.length === 0) return;
  const orderNos = selectedOrders.value.map(o => o.orderNo);
  //状态都是待提现
  const statusCount: number = selectedOrders.value.map(m => m.withdrawStatus).filter(s => s !== 0).length;
  if (statusCount > 0) {
    message.alertError("请选择状态为【待提现】的订单进行批量提现操作，请检查数据");
    return;
  }
  ElMessageBox.confirm(`确认对 ${selectedOrders.value.length} 笔订单进行批量提现？`, '提示')
    .then(async () => {
      const res: boolean = await OrderWithdrawalApi.batchWithdraw(orderNos);
      if (res) {
        message.success('批量提现提交成功')
        // 成功后刷新列表
        await getList();
      } else {
        message.error('批量提现提交失败，请稍后再试')
      }

      // 可在此刷新列表或清空选择
      selectedOrders.value = []
    })
    .catch(() => {
      message.info('取消提现')
    })
}

const activeName = ref('')
const tabClickHandle = (tabName: string) => {
  if (tabName === "all") {
    queryParams.withdrawStatus = undefined;
  } else {
    queryParams.withdrawStatus = Number(tabName);
  }
  //queryParams.withdrawStatus = tabName === 'all' ? undefined :Number(tabName);
  handleQuery();
}
</script>